using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.Xml;

namespace TimeLogger
{
    public class TimeLogDocument
    {
        private List<DataCollections> _events = new List<DataCollections>();
        private List<OfflineProject> _projects = new List<OfflineProject>();
        private bool _dirty;
        private string _path;        

        public TimeLogDocument() { }

        public TimeLogDocument(string path)
        {
            _path = path;
        }

        public void AddEvent(DataCollections evt)
        {
            _events.Add(evt);
            _dirty = true;
            Save();
        }

        public void RemoveEvent(DataCollections evt)
        {
            _events.Remove(evt);
            _dirty = true;
            Save();
        }

        public List<DataCollections> Events
        {
            get { return _events; }
        }

        public List<OfflineProject> Projects
        {
            get { return _projects; }
        }

        public void SetDirty(bool dirty)
        {
            _dirty = dirty;
        }

        public void SetDirty()
        {
            _dirty = true;
        }

        [XmlIgnore()]
        public string Path
        {
            get { return _path; }
            set { _path = value; }
        }

        private void Save(string filename)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(TimeLogDocument));
            XmlTextWriter writer = new XmlTextWriter(filename, null);
            writer.Formatting = Formatting.Indented;
            serializer.Serialize(writer, this);
            writer.Close();
        }

        public void Save()
        {
            if (_dirty)
            {
                Save(_path);
            }
        }

        public void ForceSave()
        {
            Save(_path);
        }

        static public TimeLogDocument Open(string filename)
        {
            XmlTextReader reader = new XmlTextReader(filename);
            XmlSerializer serializer = new XmlSerializer(typeof(TimeLogDocument));
            TimeLogDocument doc = (TimeLogDocument)serializer.Deserialize(reader);
            reader.Close();
            if (doc != null)
            {
                doc.Path = filename;
                doc.SetDirty(false);
            }
            return doc;
        }
    }
}
